package example.beans;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

//import org.ajax4jsf.model.KeepAlive;

import example.model.Project;

import java.io.Serializable;
import java.sql.*;

//@KeepAlive
//@org.ajax4jsf.model.KeepAlive
//@SuppressWarnings("serial")
public class ProjectBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	private List <Project>projects;
 
	public List <Project>getProjects() {
		return projects;
	}
 
 @PostConstruct
 	public void init () {  
 		projects = new ArrayList <Project>();
  
		  Connection con = null;
		  try {
		   //Class.forName("com.mysql.jdbc.Driver");
		   String url = "jdbc:mysql://localhost:3306/dbagatha";
		   con = DriverManager.getConnection(url, "root","12345");
		   Statement st = con.createStatement();
		   ResultSet rs = st.executeQuery("select * from project");
		   while (rs.next()) {

			   projects.add (new Project(rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)));
		   }
		  } catch (Exception e) {
		   e.printStackTrace();
		   System.out.println("Exception: " + e.getMessage());
		  } finally {
		   try {
		    if (con != null)
		     con.close();
		   } catch (SQLException e) {
		    
		   }
		  }
		  
 		rowsToUpdate =  new HashSet<Integer>(); 
 	} 

	private Project selectedProject;

	public Project getSelectedProject() {
		return selectedProject;
	}
	public void setSelectedProject(Project selectedProject) {
		this.selectedProject = selectedProject;
	}

	private Set <Integer>rowsToUpdate;
	
	public Set <Integer>getRowsToUpdate() {
		return rowsToUpdate;
	}
	public void save (ActionEvent event) {
	  
		rowsToUpdate.clear();
		rowsToUpdate.add(projects.indexOf(selectedProject));
	} 
 
 
 	private DataSource dataSource;

 	public void Database(String jndiname) {
 		try {
 			dataSource = (DataSource) new InitialContext().lookup("java:comp/env/" + "dbagatha");
 		} 
 		catch (NamingException e) {
 		}
 	}

 	public Connection getConnection() throws SQLException {
 		return dataSource.getConnection();
 	}


}  

